package com.example.composeplayground.common

import com.blankj.utilcode.util.GsonUtils
import com.example.composeplayground.exceptions.AlertException
import com.example.composeplayground.exceptions.ToastException
import com.example.composeplayground.exceptions.UnauthorizedException
import com.example.composeplayground.models.OM
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import kotlin.reflect.javaType
import kotlin.reflect.typeOf

object RequestUtils {
    @OptIn(ExperimentalStdlibApi::class)
    suspend inline fun <reified T> get(url: String): OM<T> = withContext(Dispatchers.IO) {
        val client = OkHttpClient()
        val builder = Request.Builder().url(url)
        val token = TokenUtils.getToken()
        if (token != null) {
            builder.header("Authorization", token)
        }
        val request = builder.build()
        val call = client.newCall(request)
        val response = call.execute()
        withContext(Dispatchers.Main) {
            when (response.code) {
                200 -> {
                    val om =
                        GsonUtils.fromJson<OM<T>>(response.body?.string(), typeOf<OM<T>>().javaType)
                    when (om.code) {
                        1 -> throw ToastException(om.message)
                        2 -> throw AlertException(om.message)
                        else -> om
                    }
                }

                401 -> throw UnauthorizedException()
                else -> throw ToastException("网络错误")
            }
        }
    }
}